package com.sanyue.springboot.config;

import com.sanyue.springboot.servlet.Listener;
import com.sanyue.springboot.servlet.MyServlet;
import com.sanyue.springboot.servlet.SbFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.RegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;

/**
 * RegistrationBean的方式注入三大件
 * @author: Guan
 **/
//@Configuration：表示这是一个配置类
//proxyBeanMethods = true:每个Bean方法调用返回的组件都是单例的，是代理方式
@Configuration(proxyBeanMethods = true)
public class RegisterConfig {

    //以RegistrationBean的方式注入原生Servlet
    @Bean
    public ServletRegistrationBean servletTest(){
        //创建原生Servlet对象
        MyServlet myServlet = new MyServlet();
        //把原生Servlet对象关联到ServletRegistrationBean
        //"servlet03","servlet04"就是注入Servlet的url—pattern
        return new ServletRegistrationBean(myServlet,"/servlet03","/servlet04");

    }

    //注入Filter
    @Bean
    public FilterRegistrationBean filterTest(){
        SbFilter sbFilter = new SbFilter();
        FilterRegistrationBean<SbFilter> filterRegistrationBean = new FilterRegistrationBean<>(sbFilter);
        //设置filter的url-pattern
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/css/*", "/images/*"));
        return  filterRegistrationBean;
    }

    //注入Listener
    //注意，有的时候有缓存可能访问的时候不再经过过滤器，这时候刷新页面即可
    @Bean
    public ServletListenerRegistrationBean listenerTest(){
        Listener listener = new Listener();
        ServletListenerRegistrationBean<Listener> servletListenerRegistrationBean = new ServletListenerRegistrationBean<>(listener);
        return servletListenerRegistrationBean;
    }
}